package com.example.demo.demos.web.controller;

import com.example.demo.demos.web.service.ExcelService;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/excel")
public class ExcelController {

    private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(ExcelController.class);
    @CrossOrigin(origins = "http://localhost:63342")
    @PostMapping("/upload")
    public ResponseEntity<String> uploadFiles(@RequestParam("files") MultipartFile[] files) {
        try {
            // 获取项目根目录下的 uploads 文件夹路径
            String uploadsPath = System.getProperty("user.dir") + File.separator + "uploads";
            File uploadsDir = new File(uploadsPath);

            // 检查并创建目录
            if (!uploadsDir.exists()) {
                boolean created = uploadsDir.mkdir(); // 创建目录
                if (!created) {
                    logger.error("创建 uploads 的目录时失败.");
                    return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("创建 uploads 的目录时失败.");
                }
            }

            // 保存文件
            List<File> savedFiles = new ArrayList<>();
            for (MultipartFile file : files) {
                if (!file.isEmpty() && isValidExcelFile(file)) {
                    // 保存文件到 uploads 文件夹 ,避免文件名重复
                    String uniqueFileName = System.currentTimeMillis() + "_" + file.getOriginalFilename();
                    File savedFile = new File(uploadsDir, uniqueFileName);
                    file.transferTo(savedFile);
                    savedFiles.add(savedFile);
                } else {
                    logger.error("上传的文件格式无效，系统只允许 .xls和 .xlsx这两种类型的文件.");
                    return ResponseEntity.badRequest().body("上传的文件格式无效，系统只允许 .xls和 .xlsx这两种类型的文件.");
                }
            }

            // 调用业务逻辑处理文件
            File summaryFile = ExcelService.processFilesWithHeaderMapping(savedFiles);

            // 文件处理成功后，删除临时保存的文件
            for (File savedFile : savedFiles) {
                if (savedFile.exists()) {
                    boolean deleted = savedFile.delete();
                    if (!deleted) {
                        // 记录日志
                        System.out.println("删除临时文件失败: " + savedFile.getAbsolutePath());
                    }
                }
            }
            ResponseEntity<String> ok = ResponseEntity.ok("文件合并成功. Download summary from: /excel/download");
            return ok;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("文件合并失败.", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("文件合并失败.");
        }
    }



    /**
     * 验证是否为有效的 Excel 文件
     *
     * @param file 上传的文件
     * @return true 如果是 .XLS 或 .XLSX 格式
     */
    private boolean isValidExcelFile(MultipartFile file) {
        String filename = file.getOriginalFilename();
        filename = filename.toLowerCase();
        return filename != null && (filename.endsWith(".xls") || filename.endsWith(".xlsx"));
    }

    @CrossOrigin(origins = "http://localhost:63342")
    @GetMapping("/download")
    public ResponseEntity<InputStreamResource> downloadSummary() throws IOException {
        File file = new File("uploads/试验数据统计表.xlsx");
        InputStreamResource resource = new InputStreamResource(new FileInputStream(file));
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=summary.xlsx");
        return ResponseEntity.ok()
                .headers(headers)
                .contentLength(file.length())
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .body(resource);
    }


}
